package cn.net.qinling.xmlaccess;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import oracle.jdbc.OraclePreparedStatement;
import oracle.xdb.XMLType;

public class OracleDataAccess extends JDBCDataAccess {

/*	private static final String INSERT_SQL = "insert into documents values (?, ?)";

	private static final String QUERY_RECORD_UID = "select * from documents where id=\"%s\"";

	private static final String QUERY_RECORD_PATIENTID = "select id from documents where XMLEXISTS('declare default element namespace \"urn:hl7-org:v3\"; $d/ClinicalDocument/recordTarget/patientRole/id[@root=\"SD.4.2\" and @extension=\"%s\"]' passing content as \"d\")";

	private static final String QUERY_PATIENT_CITY_SEX = "select id from documents where XMLEXISTS ('declare default element namespace \"urn:hl7-org:v3\"; $d/ClinicalDocument/recordTarget/patientRole[addr/city=\"%s\" and patient/administrativeGenderCode/@code=\"%s\"]' passing content as \"d\")";
	
	private static final String QUERY_RECORD_AUTHOR_ADDR = "select id from documents where XMLEXISTS ('declare default element namespace \"urn:hl7-org:v3\"; $d/ClinicalDocument/author/assignedAuthor/representedOrganization/name[contains(text(), \"%s\")]' passing content as \"d\")";
*/
	
	public OracleDataAccess() throws SQLException {
		DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
		this.conn = DriverManager.getConnection(DBConfiguration.ORACLE_DB_URL,
				DBConfiguration.ORACLE_DB_USERNAME,
				DBConfiguration.ORACLE_DB_PASSWORD);
	}

	@Override
	public void insert(String uid, String content) {
		OraclePreparedStatement stmt = null;
		try {
			XMLType xmlContent = XMLType.createXML(conn, content);
			stmt = (OraclePreparedStatement) this.conn
					.prepareStatement(INSERT_SQL);
			stmt.setString(1, uid);
			stmt.setObject(2, xmlContent);
			stmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (null != stmt) {
				try {
					stmt.close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	@Override
	public String getRecordById(String uid) {
		try {
			String sql = String.format(QUERY_RECORD_UID, uid);
			PreparedStatement stmt = this.conn.prepareStatement(sql);
			ResultSet rs = stmt.executeQuery();

			while (rs.next()) {
				XMLType xml = (XMLType) rs.getObject(2);
				return xml.getStringVal();
			}
			stmt.close();
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
		return null;
	}
}
